package com.mew.common.dc.redis;

import cn.hutool.core.util.RandomUtil;
import com.mew.common.config.RedisConstantValue;
import com.mew.common.rest.bo.MewSession;
import com.mew.common.util.RandomIdUtil;
import com.zebra.common.OnlineType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class AucRedisService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public AucRedisService(RedisTemplate<String, Object> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    public long getToken(){
        return RandomIdUtil.getToken();
    }

    public void putSession(MewSession session){
        if (null == session || session.uid  < 1){
            return;
        }
        redisTemplate.opsForHash().put(RedisConstantValue.SESSION_USER, session.uid, session);
    }


    public MewSession getSession(long userId){
        return (MewSession) redisTemplate.opsForHash().get(RedisConstantValue.SESSION_USER, userId);
    }

    public void removeSession(long userId){
        redisTemplate.opsForHash().delete(RedisConstantValue.SESSION_USER, userId);
    }


    public void webLogin(MewSession session){
        putSession(session);
        int timeOut = RandomUtil.randomInt(40, 70);
        redisTemplate.opsForValue().set(RedisConstantValue.SESSION_EXPIRE + session.uid, String.valueOf(timeOut), timeOut, TimeUnit.SECONDS);
    }


    public void exitGame(long userId){
         MewSession mewSession = getSession(userId);
         mewSession.exitGame();
         putSession(mewSession);  // long tk = ExitType.Exit == exitType ? getToken() : mewSession.tk;

    }


    public void chessBetLock(long userId, int overTime){
        MewSession mewSession = getSession(userId);
        mewSession.playLock(overTime);
        putSession(mewSession);

    }


    public void updateSession(long userId, MewSession other){

        MewSession mewSession = getSession(userId);
        mewSession.update(other);
        putSession(mewSession);

    }

    public void onlineSession(long userId, MewSession other){
        MewSession mewSession = getSession(userId);
        redisTemplate.executePipelined(new SessionCallback(){
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.delete(RedisConstantValue.SESSION_EXPIRE + userId);
                other.onl = OnlineType.Online.value();
                mewSession.update(other);
                redisOperations.opsForHash().put(RedisConstantValue.SESSION_USER, mewSession.uid, mewSession);
                return null;
            }
        });
    }

    public void offlineSession(long userId, long localTk){
        MewSession session = getSession(userId);
        if (null == session || session.tk != localTk || session.onl != OnlineType.Online.value()){
            return ;
        }
        redisTemplate.executePipelined(new SessionCallback(){
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                session.onl = OnlineType.OffLine.value();
                redisOperations.opsForHash().put(RedisConstantValue.SESSION_USER, session.uid, session);
                redisOperations.opsForValue().set(RedisConstantValue.SESSION_EXPIRE + userId, "1800",1800, TimeUnit.SECONDS);
                return null;
            }
        });
    }

    public void offlineSession(long userId){
        MewSession session = getSession(userId);
        if (null == session || session.onl != OnlineType.Online.value()){
            return ;
        }

        redisTemplate.executePipelined(new SessionCallback(){
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                session.onl = OnlineType.OffLine.value();
                redisOperations.opsForHash().put(RedisConstantValue.SESSION_USER, session.uid, session);
                int random = RandomUtil.randomInt(1800, 2400);
                redisOperations.opsForValue().set(RedisConstantValue.SESSION_EXPIRE + userId, String.valueOf(random), random, TimeUnit.SECONDS);
                return null;
            }
        });
    }


    // 在线人数上万需要优化
    public List<MewSession> findOnlineByGid(List<Integer> gamdIds){
        List<Object> list = redisTemplate.opsForHash().values(RedisConstantValue.SESSION_USER);
        if (null == list || list.isEmpty()){
            return null;
        }
        return list.stream().map(o -> (MewSession)o).filter(ses -> ses.onl == OnlineType.Online.value() && gamdIds.contains(ses.loc)).collect(Collectors.toList());
    }

    // 在线人数上万需要优化
    public List<MewSession> findOnlineBySid(int sid, int serverType){
        List<Object> list = redisTemplate.opsForHash().values(RedisConstantValue.SESSION_USER);
        if (null == list || list.isEmpty()){
            return null;
        }

        return list.stream().map(o -> (MewSession)o)
                .filter(ses -> ses.onl == OnlineType.Online.value()
                                    && ((serverType == 0 && ses.lsid == sid) || (serverType > 0 && ses.gsid == sid)) )
                .collect(Collectors.toList());
    }

    public List<MewSession> findALL(){
        List<Object> list = redisTemplate.opsForHash().values(RedisConstantValue.SESSION_USER);
        if (null == list || list.isEmpty()){
            return null;
        }
        return list.stream().map(o -> (MewSession)o).collect(Collectors.toList());
    }


    public boolean getMaintenance(){
        Object v = redisTemplate.opsForValue().get(RedisConstantValue.CONFIG_MAINTAIN);
        return v != null ? true : false;
    }



}
